package com.hdjk.view.activity.financial;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.hdjk.view.R;
import com.hdjk.view.adapter.FinancialListAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.entity.FinancialEntity;
import com.hdjk.view.network.FinancialNetWork;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 理财产品列表页
 * Created by sxy on 2017/11/2.
 */

public class FinancialListActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, FinancialListAdapter.OnBuyClickListener {

    private List<FinancialEntity> mList;
    private FinancialListAdapter mAdapter;

    private int lastItem, totalItem;
    // Content View Elements
    private SwipeRefreshLayout mSwipeLayout;
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private ImageView tv_top;
    private ListView lv_data_list;
    // End Of Content View Elements

    private void bindViews() {
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_ly);
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        tv_top = (ImageView) findViewById(R.id.tv_top);
        lv_data_list = (ListView) findViewById(R.id.lv_data_list);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_financial_list);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        ttb_title_bar.setNavTitle("好得理财");
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.bg_common_red, R.color.bg_common_red,
                R.color.bg_common_red, R.color.bg_common_red);
        // 设置手指在屏幕下拉多少距离会触发下拉刷新
        mSwipeLayout.setDistanceToTriggerSync(200);
//        tv_top.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                return false;
//            }
//        });
        tv_top.setFocusable(true);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        ViewGroup.LayoutParams layoutParams = tv_top.getLayoutParams();
        layoutParams.width = dm.widthPixels;
        layoutParams.height = (int) ((float) (dm.widthPixels) / 1080 * 494);
        tv_top.setLayoutParams(layoutParams);
    }

    @Override
    protected void initData() {
        mList = new ArrayList<>();
        mAdapter = new FinancialListAdapter(this, this);
        mAdapter.setDataList(mList);

        lv_data_list.setAdapter(mAdapter);
        lv_data_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int index = (int) id;
                Intent intent = new Intent(FinancialListActivity.this, FinancialDetailActivity.class);
                intent.putExtra("id", mList.get(index).getProductCode());
                intent.putExtra("state", mList.get(index).getIsBuyEnable());
                startActivity(intent);
            }
        });
        lv_data_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                boolean enable = false;
                if (lv_data_list != null && lv_data_list.getChildCount() > 0) {
                    // check if the first item of the list is visible
                    boolean firstItemVisible = lv_data_list.getFirstVisiblePosition() == 0;
                    // check if the top of the first item is visible
                    boolean topOfFirstItemVisible = lv_data_list.getChildAt(0).getTop() == 0;
                    // enabling or disabling the refresh layout
                    enable = firstItemVisible && topOfFirstItemVisible;
                }
                mSwipeLayout.setEnabled(enable);
            }
        });
        getNetworkList();
    }


    private void getNetworkList() {
        mDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("pageIndex", 1);
            object.put("pageSize", 10);
            FinancialNetWork.getFinancialList(UserTokenUtil.getToken(FinancialListActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (mSwipeLayout.isRefreshing()) {
                        mSwipeLayout.setRefreshing(false);
                    }
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && !TextUtils.isEmpty(msg.getData().toString())) {
                        List<FinancialEntity> list = (ArrayList) msg.getData();
                        if (list != null) {
                            for (int i = 0; i < list.size(); i++) {
                                FinancialEntity entity = list.get(i);
                                if (entity.getIsBuyEnable().equals("Y")) {
                                    mList.add(entity);
                                }
                            }
                            for (int i = 0; i < list.size(); i++) {
                                FinancialEntity entity = list.get(i);
                                if (entity.getIsBuyEnable().equals("N")) {
                                    mList.add(entity);
                                }
                            }
                            if (mAdapter == null) {
                                mAdapter = new FinancialListAdapter(FinancialListActivity.this, FinancialListActivity.this);
                                mAdapter.setDataList(mList);
                                lv_data_list.setAdapter(mAdapter);
                            } else {
                                mAdapter.setDataList(mList);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
        }
    }

    @Override
    public void onRefresh() {
        getNetworkList();
    }

    @Override
    public void onBuyClick(final FinancialEntity financialEntity) {
//        if (UserTokenUtil.isLogin(FinancialListActivity.this)) {
//            if (UserTokenUtil.isOpenAccount(FinancialListActivity.this)) {
//                MyAlertDialog alertDialog = new MyAlertDialog(FinancialListActivity.this, "您将使用奕丰金融提供的基金销售服务", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Intent intent = new Intent(FinancialListActivity.this, FinancialBuyActivity.class);
//                        intent.putExtra("id", financialEntity.getProductCode());
//                        startActivity(intent);
//                    }
//                });
//                alertDialog.show();
//                mDialog.show();
//                JSONObject object = new JSONObject();
//                try {
//                    object.put("fundCode", financialEntity.getProductCode());
//                    FundNetWork.getFundDetail(UserTokenUtil.getToken(FinancialListActivity.this), object.toString(), new CallBackListener() {
//                        @Override
//                        public void onCallBackCompleted(Msg msg) {
//                            mDialog.cancel();
//                            if (msg != null && msg.getSuccess() && msg.getData() != null&&msg.getData() instanceof FundEntity) {
//                                FundEntity fundEntity = (FundEntity) msg.getData();
//                                Intent intent = new Intent(FinancialListActivity.this, FundBuyActivity.class);
//                                Bundle bundle = new Bundle();
//                                bundle.putSerializable("fund", fundEntity);
//                                intent.putExtras(bundle);
//                                FinancialListActivity.this.startActivity(intent);
//                            }
//                        }
//                    });
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            } else {
//                ToastUtils.showShortToast(FinancialListActivity.this, "开户后才能购买基金");
//                Intent intent = new Intent(FinancialListActivity.this, OpenAccountActivity.class);
//                startActivity(intent);
//            }
//        } else {
//            Intent intent = new Intent(FinancialListActivity.this, LoginActivity.class);
//            startActivity(intent);
//        }
        Intent intent = new Intent(FinancialListActivity.this, FinancialDetailActivity.class);
        intent.putExtra("id", financialEntity.getProductCode());
        intent.putExtra("state", financialEntity.getIsBuyEnable());
        startActivity(intent);
    }
}
